package com.hxm.demo.test1;

/**
 * @author huangxiaoming
 * @date 2022/10/3
 **/
public class TestLinkedSum {

    /**
     * 链表求和
     * 2. 两数相加
     * @param args
     */
    public static void main(String[] args) {
        ListNode l1 = new ListNode(2, new ListNode(4, new ListNode(3)));
        ListNode l2 = new ListNode(5, new ListNode(6, new ListNode(4)));

        System.out.println(addTwoNumbers(l1, l2));

    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null;
        ListNode tail = null;
        int mod = 0;
        while (l1 != null || l2 != null) {
            int n = l1 != null ? l1.val : 0;
            int m = l2 != null ? l2.val : 0;
            int sum = n + m + mod;
            if (head == null) {
                head = tail = new ListNode(sum % 10);
            } else {
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
            }
            mod = sum / 10;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }

        if (mod > 0) {
            tail.next = new ListNode(mod);
        }
        return head;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}


